const { chromium } = require('playwright');

(async () => {
  console.log('正在连接到端口 9222 的 Edge 浏览器...');
  
  try {
    const browser = await chromium.connectOverCDP('http://localhost:9222');
    const context = browser.contexts()[0];
    const pages = context.pages();
    
    console.log('连接成功！');
    console.log('═══════════════════════════════════════════════════════');
    console.log('录制模式已启动！');
    console.log('- 支持多窗口/多标签页录制');
    console.log('- 页面跳转自动重新注入');
    console.log('- 按 Ctrl+C 退出');
    console.log('═══════════════════════════════════════════════════════\n');
    
    // ==================== 日志处理 ====================
    const logAction = (action) => {
      const divider = '═'.repeat(60);
      const line = '─'.repeat(60);
      
      console.log(`\n${divider}`);
      
      if (action.type === 'click') {
        console.log('🖱️  点击事件');
        console.log(line);
        console.log(`元素类型: ${action.elementInfo.tagName}`);
        if (action.elementInfo.id) console.log(`ID: ${action.elementInfo.id}`);
        if (action.elementInfo.className) console.log(`Class: ${action.elementInfo.className}`);
        if (action.elementInfo.text) console.log(`文本内容: ${action.elementInfo.text}`);
        if (action.elementInfo.href) console.log(`链接: ${action.elementInfo.href}`);
        console.log(line);
        console.log(`选择器: ${action.selector}`);
        console.log(line);
        console.log(`await page.click('${action.selector}');`);
      } else if (action.type === 'fill') {
        console.log('⌨️  填写输入框');
        console.log(line);
        console.log(`选择器: ${action.selector}`);
        console.log(`值: ${action.value}`);
        console.log(line);
        console.log(`await page.fill('${action.selector}', '${action.value}');`);
      } else if (action.type === 'press') {
        console.log('⏎  按键');
        console.log(line);
        console.log(`选择器: ${action.selector}`);
        console.log(`按键: ${action.key}`);
        console.log(line);
        console.log(`await page.press('${action.selector}', '${action.key}');`);
      }
      
      console.log(`${divider}\n`);
    };
    
    // ==================== 页面跟踪 ====================
    const processedPages = new Set();
    const injectedUrls = new Map(); // 页面对象 -> 已注入的URL
    
    // ==================== 录制器注入 ====================
    const injectRecorder = async (page) => {
      const currentUrl = page.url();
      
      // 防止重复注入同一URL
      if (injectedUrls.get(page) === currentUrl) {
        return;
      }
      
      injectedUrls.set(page, currentUrl);
      
      await page.evaluate(() => {
        // 如果已注入，跳过
        if (window.__recorderInjected) return;
        window.__recorderInjected = true;
        
        // ========== 选择器生成 ==========
        function generateSelector(element) {
          if (element.hasAttribute('data-testid')) {
            return `[data-testid="${element.getAttribute('data-testid')}"]`;
          }
          if (element.id) {
            return `#${element.id}`;
          }
          if (element.hasAttribute('aria-label')) {
            return `[aria-label="${element.getAttribute('aria-label')}"]`;
          }
          if (element.hasAttribute('placeholder')) {
            return `[placeholder="${element.getAttribute('placeholder')}"]`;
          }
          
          // 文本选择器
          const text = element.textContent?.trim();
          if (text && text.length > 0 && text.length < 50) {
            const tag = element.tagName.toLowerCase();
            if (['button', 'a', 'span', 'div'].includes(tag)) {
              return `${tag}:has-text("${text}")`;
            }
          }
          
          // 类名选择器
          if (element.className && typeof element.className === 'string') {
            const classes = element.className.split(' ').filter(c => c && !c.match(/^(css-|sc-|_)/));
            if (classes.length > 0) {
              return `.${classes[0]}`;
            }
          }
          
          // nth-child 作为最后手段
          const parent = element.parentElement;
          if (parent) {
            const index = Array.from(parent.children).indexOf(element) + 1;
            const tag = element.tagName.toLowerCase();
            return `${parent.tagName.toLowerCase()} > ${tag}:nth-child(${index})`;
          }
          
          return element.tagName.toLowerCase();
        }
        
        // ========== 元素高亮 ==========
        let highlightBox = null;
        
        function createHighlight() {
          if (!highlightBox) {
            highlightBox = document.createElement('div');
            highlightBox.style.cssText = `
              position: fixed;
              border: 2px solid #e74c3c;
              background: rgba(231, 76, 60, 0.1);
              pointer-events: none;
              z-index: 999999;
              transition: all 0.1s ease;
            `;
            document.body.appendChild(highlightBox);
          }
          return highlightBox;
        }
        
        function showHighlight(element) {
          const box = createHighlight();
          const rect = element.getBoundingClientRect();
          box.style.left = rect.left + 'px';
          box.style.top = rect.top + 'px';
          box.style.width = rect.width + 'px';
          box.style.height = rect.height + 'px';
          box.style.display = 'block';
        }
        
        function hideHighlight() {
          if (highlightBox) {
            highlightBox.style.display = 'none';
          }
        }
        
        // ========== 事件监听 ==========
        document.addEventListener('mouseover', (e) => {
          if (e.target !== highlightBox) {
            showHighlight(e.target);
          }
        }, true);
        
        document.addEventListener('mouseout', () => {
          hideHighlight();
        }, true);
        
        // 点击事件（带防抖）
        let lastClick = { time: 0, target: null };
        document.addEventListener('click', (e) => {
          const now = Date.now();
          if (e.target === lastClick.target && now - lastClick.time < 100) {
            return; // 防止重复点击
          }
          lastClick = { time: now, target: e.target };
          
          if (window.__logAction) {
            window.__logAction({
              type: 'click',
              selector: generateSelector(e.target),
              elementInfo: {
                tagName: e.target.tagName.toLowerCase(),
                id: e.target.id || '',
                className: e.target.className || '',
                text: e.target.textContent?.trim().substring(0, 50) || '',
                href: e.target.href || ''
              }
            });
          }
        }, true);
        
        // 输入事件
        document.addEventListener('input', (e) => {
          if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
            if (window.__logAction) {
              window.__logAction({
                type: 'fill',
                selector: generateSelector(e.target),
                value: e.target.value
              });
            }
          }
        }, true);
        
        // 按键事件
        document.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) {
            if (window.__logAction) {
              window.__logAction({
                type: 'press',
                selector: generateSelector(e.target),
                key: 'Enter'
              });
            }
          }
        }, true);
        
        // ========== 视觉提示 ==========
        const tip = document.createElement('div');
        tip.textContent = '✅ 录制器已激活';
        tip.style.cssText = `
          position: fixed;
          top: 10px;
          right: 10px;
          background: #2ecc71;
          color: white;
          padding: 10px 20px;
          border-radius: 5px;
          z-index: 9999999;
          font-family: Arial, sans-serif;
          font-size: 14px;
          box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        `;
        document.body.appendChild(tip);
        setTimeout(() => tip.remove(), 3000);
      });
    };
    
    // ==================== 页面设置 ====================
    const setupPage = async (page) => {
      if (processedPages.has(page)) return;
      processedPages.add(page);
      
      console.log(`🆕 新页面检测到: ${page.url()}`);
      
      // 暴露日志函数
      try {
        await page.exposeFunction('__logAction', logAction);
      } catch (e) {
        // 已暴露，忽略
      }
      
      // 监听页面跳转
      page.on('load', async () => {
        const url = page.url();
        if (injectedUrls.get(page) !== url) {
          console.log(`\n🌐 页面跳转: ${url}`);
          console.log(`await page.goto('${url}');\n`);
          
          await page.waitForLoadState('domcontentloaded');
          await page.waitForTimeout(500);
          await injectRecorder(page);
          console.log('✅ 录制器已重新注入\n');
        }
      });
      
      // 监听页面关闭
      page.on('close', () => {
        processedPages.delete(page);
        injectedUrls.delete(page);
        console.log('📤 页面已关闭\n');
      });
      
      // 首次注入
      await page.waitForLoadState('domcontentloaded').catch(() => {});
      await page.waitForTimeout(300);
      await injectRecorder(page);
      console.log('✅ 录制器已就绪\n');
    };
    
    // ==================== 启动 ====================
    // 监听新窗口
    context.on('page', async (newPage) => {
      console.log('\n🎉 检测到新窗口/标签页');
      await setupPage(newPage);
    });
    
    // 设置所有已存在的页面
    console.log(`正在为 ${pages.length} 个页面设置录制器...\n`);
    for (const page of pages) {
      await setupPage(page);
    }
    
    console.log('💡 所有窗口和标签页的操作都会被记录\n');
    
    // 保持运行
    await new Promise(() => {});
    
  } catch (error) {
    console.error('连接失败:', error.message);
    console.log('\n请确保：');
    console.log('1. Edge 浏览器已以调试模式启动');
    console.log('2. 运行命令: start msedge.exe --remote-debugging-port=9222 --user-data-dir="edge-debug-profile"');
    console.log('3. 或运行 start-edge.bat 文件');
    process.exit(1);
  }
})();
